package com.xiaoma.service;

import com.xiaoma.entity.User;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.apache.tomcat.jdbc.pool.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author xiaomacdut
 * @date 2019年9月1日 上午9:28:54
 */
//@Service
public class UserService{


    @Autowired
    private JdbcTemplate jdbctemplate;

    @Autowired
    private DataSource dataSource;

    @Autowired
    private AdminService adminService;

    @PostConstruct
    public Userdao test(){
        Userdao userdao = (name)->  adminService.getUser(name);
        return userdao;
   /*     Userdao userdao = (name) -> {return "aaa"+name;};
        userdao.getUser("bb");
        return userdao;*/
    }





    @Transactional
    public void addUser(User user){
        jdbctemplate.update("insert into user(UserName,PassWord) values (?,?)", user.getUserName(),
                user.getPassWord());
    }
    
    public void addUserList(List<User> users){
        List<Object []> datas = new ArrayList<>();
        for(User s : users){
            datas.add(new Object[]{s.getUserName(), s.getPassWord()});
        }
        jdbctemplate.batchUpdate("insert into user(UserName,PassWord) values (?,?)", datas);
    }
    
    public User getUserById(Integer id){
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
        return jdbctemplate.queryForObject("select * from user where Id = ?", rowMapper, id);
    }
    
    @Transactional
    public void updateUserByName(String PassWord, String UserName){
        jdbctemplate.update("update user SET PassWord = ? WHERE UserName = ?", new Object[]{PassWord, UserName});
    }

//    @Transactional
    public List<User> getUsers() throws SQLException {
        /*
         * 功能描述:
         */
        RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);


        List<User> query = jdbctemplate.query("select * from user", rowMapper);
//        Connection connection = jdbctemplate.getDataSource().getConnection();
//        System.out.println("idle:"+dataSource.getPool().  getIdle());
        return query;

    }
    
    public Long getUsersSize(){
        return jdbctemplate.queryForObject("select count(Id) from user", Long.class);
    }
}
